package com.jxmcloud.business.cut.util;

import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jxmcloud.business.ce.model.CeSysParameter;
import com.jxmcloud.business.ce.service.CeSysParameterService;
import com.jxmcloud.business.cut.dto.client.CouponParamDto;
import com.jxmcloud.business.cut.feign.vip.VipClientNew;
import com.jxmcloud.business.cut.vo.vip.UserOrderCountVo;
import com.jxmcloud.business.cut.vo.vip.UserOrderVo;
import com.xlcloud.platform.api.config.Constant;
import com.xlcloud.platform.util.PublicUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author chr
 */
@Slf4j
@Component
public class VipRpcUtil {
    @Resource
    private VipClientNew vipClient;
    @Resource
    private CeSysParameterService ceSysParameterService;
    @Resource
    private DiscoveryClient discoveryClient;  // 新增注册中心客户端


    /**
     * 获取VIP服务实例的IP地址
     */
    public String getVipServiceInternalIp() {
        List<ServiceInstance> instances = discoveryClient.getInstances("BUSINESS-VIP-SERVICE");
        if (!instances.isEmpty()) {
            // 随机可用实例的IP（可根据需要实现负载均衡策略）
            int i = RandomUtil.randomInt(0, instances.size());
            return instances.get(i).getHost() + ":" + instances.get(i).getPort();
        }
        return null;
    }

    /**
     * 查询用户最近购买商品列表
     *
     * @return 商品列表
     */
    public UserOrderCountVo getUserRecentBuyList(String loginName, Integer pageNum, Integer pageSize, String startTime) {
        TimeInterval interval = new TimeInterval();
        UserOrderCountVo userOrderCountVo = new UserOrderCountVo();
        try {
            String result = vipClient.getUserRecentBuyList(loginName,pageNum,pageSize,startTime);
            if (PublicUtil.isEmpty(result)) {
                return null;
            }
            JSONObject body = JSONObject.parseObject(result);
            if (PublicUtil.isEmpty(body.get(Constant.KEY_DATA))) {
                return null;
            }
            List<UserOrderVo> goodsList = JSONArray.parseArray(body.getJSONObject(Constant.KEY_DATA).getString("goodsList"), UserOrderVo.class);
            userOrderCountVo.setUserOrderVoList(goodsList);
        } catch (Exception e) {
            log.error("查询用户最近购买商品列表异常耗时时长：{}",interval.intervalRestart());
            log.error("查询vip最近购物失败{}",e);
        }
        return userOrderCountVo;
    }
    /**
     * 查询用户最近购买商品数量
     *
     * @return 商品列表
     */
    public Integer getUserTotalBuyNum(String loginName, String buyDate) {
        Integer totalBuyNum = 0;
        TimeInterval interval = new TimeInterval();
        try {
            String result = vipClient.getUserTotalBuyNum(loginName,buyDate);
            if (PublicUtil.isEmpty(result)) {
                return totalBuyNum;
            }
            JSONObject body = JSONObject.parseObject(result);
            if (PublicUtil.isEmpty(body.get(Constant.KEY_DATA))) {
                return totalBuyNum;
            }
            totalBuyNum = JSONObject.parseObject(body.getJSONObject(Constant.KEY_DATA).getString("num"), Integer.class);
        } catch (Exception e) {
            log.error("商品列表异常耗时时长：{}",interval.intervalRestart());
            log.error("查询用户最近购买商品数量失败{}",e);
        }
        return PublicUtil.expNotEmpty(totalBuyNum);
    }

    public boolean sendCoupon(CouponParamDto couponParamDto) {
        TimeInterval interval = new TimeInterval();
        try {
            CeSysParameter feignSwitch = ceSysParameterService.getParamByKeyCache("FEIGN_SWITCH");
            String data;
            if(feignSwitch.getParameterValue().equals("0")){
                String param = JSONUtil.toJsonStr(couponParamDto);
                String url = "http://" + getVipServiceInternalIp() + "/app/coupon/gameSendCoupon";
                data = HttpUtil.post(url, param);
                log.info("发券耗时：{}",interval.intervalRestart());
            } else {
                data = vipClient.gameSendCoupon(couponParamDto);
                log.info("发券耗时：{}",interval.intervalRestart());
            }
            if (!JSONUtil.parseObj(data).get("code").toString().equals("0")) {
                log.error("发券失败，account={}, orderNo={}, 原因:{}", couponParamDto.getLoginName(),couponParamDto.getOrderNo(),JSONUtil.parseObj(data).get("message"));
                return false;
            }
            log.info("发券成功，account={}, orderNo={}", couponParamDto.getLoginName(),couponParamDto.getOrderNo());
        } catch (Exception e) {
            log.error("发券异常耗时时长：{}",interval.intervalRestart());
            log.error("发券失败，account={}, orderNo={}, 原因:{}", couponParamDto.getLoginName(),couponParamDto.getOrderNo(),e);
        }
        return true;
    }
}









